﻿using General.Core.UnitOfWork;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace General.Entities
{
    /// <summary>
    /// 工作单元实现类
    /// </summary>
    public class UnitOfWork<TDbContext> : IUnitOfWork, IDisposable where TDbContext : DbContext
    {
        #region 数据上下文

        /// <summary>
        /// 数据上下文
        /// </summary>
        public TDbContext _dbContext;
        private DBConnectionOption _readAndWrite = null;
        public UnitOfWork(TDbContext dbContext, IOptionsMonitor<DBConnectionOption> options)
        {
            _dbContext = dbContext;
            this._readAndWrite = options.CurrentValue;
            _dbContext.Database.GetDbConnection().ConnectionString = this._readAndWrite.WriteConnection;
        }

        #endregion

        public int Commit()
        {
            return _dbContext.SaveChanges();
        }

        public async Task<int> CommitAsync()
        {
            return await _dbContext.SaveChangesAsync();
        }

        public void Dispose()
        {
            if (_dbContext != null)
            {
                _dbContext.Dispose();
            }
            GC.SuppressFinalize(this);
        }
    }
}
